package net.wanho.servlet;

import com.alibaba.fastjson.JSON;
import net.wanho.entity.Emp;
import net.wanho.exception.EmpExistsException;
import net.wanho.service.EmpService;
import net.wanho.service.impl.EmpServiceImpl;
import net.wanho.util.AjaxResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Author：汤小洋
 * Date：2024-07-30 9:32
 * Description：<描述>
 */
@WebServlet("/addEmp")
public class AddEmpServlet extends HttpServlet {

    private EmpService empService = new EmpServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("Access-Control-Allow-Origin","*");
        resp.setContentType("application/json;charset=utf8");
        PrintWriter out = resp.getWriter();

        /**
         * 获取客户端传递过来的参数，并实现业务处理
         */
        String name = req.getParameter("name");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        try{
            empService.add(new Emp(name,phone,address));

            /**
             * 响应客户端
             */
            out.print(JSON.toJSONString(AjaxResult.success("添加成功")));
        }catch(EmpExistsException e){
            out.print(JSON.toJSONString(AjaxResult.error(e.getMessage())));
        }finally {
            out.close();
        }
    }
}
